<?php
// +----------------------------------------------------------------------
// | Description: 规则
// +----------------------------------------------------------------------
// | Author: linchuangbin <linchuangbin@honraytech.com>
// +----------------------------------------------------------------------

namespace app\common\model;

use common\helper\ArrayHelper;
use common\model\base\BaseModel;
use common\traits\InstanceTrait;
use think\model\Collection;

class AdminRule extends BaseModel
{

    use InstanceTrait;

    protected $name = 'admin_rule';
    protected $pk = 'rule_id';

    /**
     * 获取器
     * @param $value
     * @param $data
     * @return string
     */
    public function getRouteAttr($value, $data)
    {
        return sprintf("%s/%s/%s", $data['module'], $data['controller'], $data['action']);
    }

    /**
     * [getDataList 获取列表]
     * @linchuangbin
     * @DateTime  2017-02-10T21:07:18+0800
     * @param string $type [是否为树状结构]
     * @return    [array]
     */
    public function getDataList($type = '')
    {
        $this->startTrans();
        $data = static::where($this->getBaseWhere())
                      ->field($this->baseField)
                      ->select();
        $data = $data->toArray();
        foreach ($data as $key => $value) {
            $data[$key]['route'] = sprintf("%s/%s/%s", $value['module'], $value['controller'], $value['action']);
        }
        // 若type为tree，则返回树状结构
        if ($type == 'tree') {
            foreach ($data as $k => $v) {
                $data[$k]['check'] = false;
            }
            $ret = ArrayHelper::array_to_tree($data, 'id', 'pid', 'child', 0, true, array('pid'));
        } else {
//            父子关系排序
            $ret = [];
            $ret = ArrayHelper::array_sort_child($data, $ret);
        }
        $this->commit();
        return $ret;
    }

    /**
     * 寻找允许$module, $controller, $action的权限id
     * @param $module
     * @param $controller
     * @param $action
     * @return array|false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getUrlRuleList($module, $controller, $action)
    {
        //寻找允许$module, $controller, $action的权限id
        $where = [
            ['module', ['=', $module], ['=', '*'], 'or'],
            ['controller', ['=', $controller], ['=', '*'], 'or'],
            ['action', ['=', $action], ['=', '*'], 'or'],
            ['status', '=', '1'],
        ];
        return static::where($where)->cache(true, 60)->field($this->pk)->select();
    }

}